package com.mp.students.controller;

import com.mp.students.entity.MpUser;
import com.mp.students.service.MPMpUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mfc
 * @since 2018-09-14
 */
@RestController
@Api(tags="用户API")
@RequestMapping("/mpUser")
public class MpUserController {

    @Autowired
    MPMpUserService mPMpUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @PostMapping("/insert")
    public MpUser insert(@RequestBody MpUser mpUser) {
        if (mPMpUserService.insert(mpUser)) {
            return mpUser;
        }
        return null;
    }

    /**
     * 手动编写缓存
     *
     * @return
     */
    @GetMapping("/selectById")
    public MpUser selectById(@RequestParam("id") String id) {
        String key = "mp:user:" + id;
        Serializable serializable = redisCacheTemplate.opsForValue().get(key);
        MpUser mpUser = null;
        if (null != serializable) {
            mpUser = (MpUser) serializable;
        } else {
            mpUser = mPMpUserService.selectById(id);
            redisCacheTemplate.opsForValue().set(key, mpUser);
        }
        return mpUser;
    }

    /**
     * 结合spring cash增加缓存
     *
     * @param id
     * @return
     */
    @GetMapping("/selectById2")
    @Cacheable(key = "'mp:user'+#id", value = "mpUser")
    public MpUser selectById2(@RequestParam("id") String id) {
        MpUser mpUser = mPMpUserService.selectById(id);
        return mpUser;
    }

    /**
     * 变动后删除缓存
     *
     * @return
     */
    @PostMapping("/update")
    @CacheEvict(key = "'mp:user'+#id", value = "mpUser", allEntries = true)
    public MpUser update(@RequestBody MpUser mpUser) {
        boolean update = mPMpUserService.updateById(mpUser);
        return mpUser;
    }

    /**
     * 启动一个流程实例
     * @return
     */
    @GetMapping("/startProcess")
    public void startProcess(){
        mPMpUserService.startProcess();
    }

    /**
     * 任务列表
     * @return
     */
    @GetMapping("/checkProcess")
    public void checkProcess(){
        mPMpUserService.checkProcess();
    }
}


